package com.hontech.desktoppastacooker.conn.usb

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import com.hontech.desktoppastacooker.app.AppContext
import com.hontech.desktoppastacooker.utils.log
import kotlinx.coroutines.CompletableDeferred

private const val ACTION_USB_PERMISSION = "USB.PERMISSION"

suspend fun openUsb(usb: UsbManager, device: UsbDevice): UsbDeviceConnection {
    val ret = usb.hasPermission(device)
    if (!ret) {
        requestPermission(usb, device)
    }
    return usb.openDevice(device)
}

private suspend fun requestPermission(usb: UsbManager, device: UsbDevice) {
    val usbReceiver = UsbPermissionReceiver()
    val filter = IntentFilter(ACTION_USB_PERMISSION)
    AppContext.registerReceiver(usbReceiver, filter)
    val intent = Intent(ACTION_USB_PERMISSION)

    val pi = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
        PendingIntent.getBroadcast(AppContext, 0, intent, PendingIntent.FLAG_MUTABLE)
    } else {
        PendingIntent.getBroadcast(AppContext, 0, intent, 0)
    }

    usb.requestPermission(device, pi)
    val ret = usbReceiver.promise.await()
    AppContext.unregisterReceiver(usbReceiver)
    if (!ret) {
        throw IllegalStateException("用户拒绝USB授权")
    }
}

private class UsbPermissionReceiver() : BroadcastReceiver() {

    val promise = CompletableDeferred<Boolean>()

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent == null) {
            return
        }
        val flag = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
        log("是否允许USB权限:$flag")
        promise.complete(flag)
    }
}
